package org.easy.validator.resolver;

import org.easy.validator.core.ValidatorImpl;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.mvc.method.annotation.PathVariableMethodArgumentResolver;

import java.io.IOException;
import java.lang.annotation.Annotation;

/**
 * @Author: volicy.xu
 * @Date: 2019/12/12
 */
public class PathVariableArgumentValidatorResolver extends PathVariableMethodArgumentResolver {



    @Override
    protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
        Object value = super.resolveName(name, parameter, request);
        validateIfApplicable(value,parameter);
        return value;
    }


    /**
     *
     * @param value
     * @param parameter
     * @throws IOException
     */
    protected void validateIfApplicable(Object value, MethodParameter parameter) throws IOException {
        validateParameter(parameter, value);
    }




    /**
     *
     * @param parameter
     * @param value
     * @throws IOException
     */
    protected void validateParameter( MethodParameter parameter,Object value) throws IOException {
        Annotation[] annotations = parameter.getParameterAnnotations();
        ValidatorImpl validator = new ValidatorImpl(null);
        for (int i = 0; annotations != null && annotations.length > 0 && i < annotations.length; i++) {
            Annotation annotation = annotations[i];
            if(ValidatorImpl.isEasyValid(annotation.annotationType())){
                ValidatorImpl.valid(annotation,value,validator);
            }
        }
    }
}
